package org.xiaov.lunasql.spring;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Bean;
import org.xiaov.lunasql.engine.config.LunaSqlConfig;
import org.xiaov.lunasql.spring.mybatis.LunaDatabaseIdProvider;
import org.xiaov.lunasql.spring.mybatis.SqlSessionFactorySmartLifecycle;

/**
 * <p>
 * LunaSqlSpringAutoConfiguration
 * </p>
 *
 * @author LunaSQL
 * @since 2024/12/18 22:37
 */
public class SpringLunaSqlConfiguration {

    /**
     * 注册LunaAutoDataSourceProxyCreator
     *
     * @param lunaSqlSpringConfigObjectProvider lunaSqlSpringConfigObjectProvider
     * @return LunaAutoDataSourceProxyCreator
     */
    @Bean
    public LunaAutoDataSourceProxyCreator lunaAutoDataSourceProxyCreator(
            ObjectProvider<LunaSqlConfig> lunaSqlSpringConfigObjectProvider) {
        if (lunaSqlSpringConfigObjectProvider.stream().findFirst().isPresent()) {
            return new LunaAutoDataSourceProxyCreator(lunaSqlSpringConfigObjectProvider.getObject());
        } else {
            return new LunaAutoDataSourceProxyCreator(null);
        }
    }

    /**
     * 设置数据库类型
     *
     * @return DatabaseIdProvider
     */
    @Bean
    public DatabaseIdProvider lunaDatabaseIdProvider() {
        return new LunaDatabaseIdProvider();
    }

    /**
     * 添加拦截器
     *
     * @return SqlSessionFactoryPostProcessor
     */
    @Bean
    public SqlSessionFactorySmartLifecycle sqlSessionFactorySmartLifecycle() {
        return new SqlSessionFactorySmartLifecycle();
    }
}
